package xyz.ranyh.jobclient.util;

import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.PendingIntent;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.JetPlayer;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.DatePicker;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import xyz.ranyh.jobclient.ModifyPasswdActivity;
import xyz.ranyh.jobclient.R;
import xyz.ranyh.jobclient.fragment.FavorityFragment;
import xyz.ranyh.jobclient.http.Resource;
import xyz.ranyh.jobclient.http.SetAlarmTask;
import xyz.ranyh.jobclient.http.StarJobTask;
import xyz.ranyh.jobclient.http.Url;

import static android.content.Context.ALARM_SERVICE;

/**
 * Created by zhaoshengping on 2016/12/28.
 */

public class StarListAdapter extends BaseAdapter {
    private Context context;
    private ArrayList<JobBean> jobs;
    private ViewClickListener listener;
    private String mAlarmTime;

    public void setListener(ViewClickListener listener) {
        this.listener = listener;
    }

    public interface ViewClickListener {
        void onClick(int i, View view, String url);
    }

    public StarListAdapter(Context context, ArrayList<JobBean> jobs) {
        this.context = context;
        this.jobs = jobs;
    }

    @Override
    public int getCount() {
        return jobs.size();
    }

    @Override
    public JobBean getItem(int i) {
        return jobs.get(i);
    }

    @Override
    public long getItemId(int i) {
        return 0;
    }



    private class ViewHolder {
        TextView mTitleView;
        TextView mPublishedDateView;
        TextView mTagsView;
        TextView mStarsView;
        TextView mOpenDateView;
        ImageButton mStarButton;
        ImageButton mAlarmButton;
    }

    @Override
    public View getView(final int i, View view, ViewGroup viewGroup) {
        ViewHolder holder = null;
        final JobBean item = getItem(i);
        if (view == null) {
            view = LayoutInflater.from(context).inflate(R.layout.home_list, viewGroup, false);
            holder = new ViewHolder();
            holder.mTitleView = (TextView) view.findViewById(R.id.jobListTitle);
            holder.mPublishedDateView = (TextView) view.findViewById(R.id.jobListTime);
            holder.mTagsView = (TextView) view.findViewById(R.id.tags_view);
            holder.mStarsView = (TextView) view.findViewById(R.id.stars_view);
            holder.mOpenDateView = (TextView) view.findViewById(R.id.open_date_view);
            holder.mStarButton = (ImageButton) view.findViewById(R.id.star_button);
            holder.mAlarmButton = (ImageButton) view.findViewById(R.id.alarm_button);
            holder.mAlarmButton.setVisibility(View.VISIBLE);

            final ViewHolder FH = holder;
            holder.mAlarmButton.setOnClickListener(new View.OnClickListener() {
                Calendar calendar = Calendar.getInstance();
                Calendar time = Calendar.getInstance();
                boolean selected = false;
                @Override
                public void onClick(View v) {
                    if (item.isValidTime()) {
                        AlertDialog.Builder builder=new AlertDialog.Builder(context);  //先得到构造器
                        builder.setTitle("取消提醒");
                        builder.setMessage("确定取消这个提醒？");
                        builder.setPositiveButton("确认", new DialogInterface.OnClickListener(){

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                mAlarmTime = "-1";
                                setAlarm(item, FH);

                            }
                        });
                        builder.setNegativeButton("取消", null);
                        builder.create().show();
                        return;
                    }

                    final TimePickerDialog timePickerDialog = new TimePickerDialog(context,
                            new TimePickerDialog.OnTimeSetListener() {
                                @Override
                                public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                                    if (selected == false) {
                                        mAlarmTime += hourOfDay + ":" + minute;
                                        if (item.isValidTime(mAlarmTime)) {
                                            setAlarm(item, FH);
                                            selected = true;
                                        } else {
                                            Toast.makeText(context, "设置时间错误。", Toast.LENGTH_SHORT).show();
                                        }

                                    } else {
                                        selected = false;
                                    }
                                }
                            },time.get(Calendar.HOUR_OF_DAY),time.get(Calendar.MINUTE),true);

                    new DatePickerDialog(context,
                            new DatePickerDialog.OnDateSetListener() {
                                @Override
                                public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                                    mAlarmTime = year + "-" + (monthOfYear + 1) + "-" + dayOfMonth + " ";
                                    timePickerDialog.show();
                                }
                            }, calendar.get(Calendar.YEAR),
                            calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH)).show();
                }
            });

            holder.mStarButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    new StarJobTask(item.getId(), Url.UNSTAR_JOB_URL) {
                        @Override
                        protected void onPostExecute(final JSONObject success) {
                            if (success != null) {
                                try {
                                    jobs.remove(i);
                                    notifyDataSetChanged();
                                    Resource.getInstance().getUser().getStar().remove((Integer)item.getId());
                                    Toast.makeText(context, success.getString("message"), Toast.LENGTH_SHORT).show();
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                        }

                    }.execute();
                }
            });

            view.setTag(holder);
        } else {
            holder = (ViewHolder) view.getTag();
        }
        holder.mTitleView.setText(item.getTitle());
        holder.mPublishedDateView.setText(item.getPublishedDate());
        holder.mTagsView.setText(item.getTagsString());
        holder.mStarsView.setText(String.valueOf(item.getFollowerCount()));
        holder.mOpenDateView.setText(item.getOpenDate());

        holder.mStarButton.setImageResource(R.drawable.star);
        holder.mAlarmButton.setImageResource(R.drawable.alarm_less);

        if (item.isValidTime()) {
            holder.mAlarmButton.setImageResource(R.drawable.alarm);
        }

        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.d("view on click", ""+i);
                String url = jobs.get(i).getRefUrl();
                listener.onClick(i,view,url);
            }
        });
        return view;
    }

    private void setAlarm(final JobBean item, final ViewHolder FH) {
        int id = item.getId();
        new SetAlarmTask(id, mAlarmTime) {
            @Override
            protected void onPostExecute(final JSONObject success) {
                if (success != null) {
                    try {
                        Toast.makeText(context, success.getString("message"), Toast.LENGTH_SHORT).show();
                        if (item.getAlarm() == "null") {
                            item.setAlarm(mAlarmTime);
                            FH.mAlarmButton.setImageResource(R.drawable.alarm);
                            Resource.getInstance().getUser().getAlarm().add(item.getId());
                        } else {
                            item.setAlarm("null");
                            FH.mAlarmButton.setImageResource(R.drawable.alarm_less);
                            Resource.getInstance().getUser().getAlarm().remove((Integer)item.getId());
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        }.execute();
    }
}
